package com.fyzk.activity.lottery.basketball;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.LayoutParams;
import android.widget.TextView;

import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.base.IBaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.lottery.basketball.JCLQFilterGameQueuePop.OnFilterListener;
import com.fyzk.activity.lottery.basketball.JCLQSelectPlayMethodPop.OnWFCheckChangedListener;
import com.fyzk.activity.lottery.basketball.fragment.JCLQDXFFragment;
import com.fyzk.activity.lottery.basketball.fragment.JCLQHGFragment;
import com.fyzk.activity.lottery.basketball.fragment.JCLQRFSFFragment;
import com.fyzk.activity.lottery.basketball.fragment.JCLQSFCFragment;
import com.fyzk.activity.lottery.basketball.fragment.JCLQSFFragment;
import com.fyzk.activity.lottery.basketball.fragment.JCLQTabBaseFragment;
import com.fyzk.activity.lottery.shuzicai.InfoDetailActivity;
import com.fyzk.activity.lottery.togetherbuy.HM_Popupwindow.HM_PopuponItemListener;
import com.fyzk.activity.myview.NoSwipeViewPager;
import com.fyzk.activity.prize.JLPrizeActivity;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.activity.user.touzhu.CommonBetActivity;
import com.fyzk.activity.zhifu.JCLQDXFPayActivity;
import com.fyzk.activity.zhifu.JCLQHGPayActivity;
import com.fyzk.activity.zhifu.JCLQRSFPayActivity;
import com.fyzk.activity.zhifu.JCLQSFCPayActivity;
import com.fyzk.activity.zhifu.JCLQSFPayActivity;
import com.fyzk.bean.JCLQResponseInfo;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.interfaces.OnBetCheckedListener;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.R;
import com.fyzk.model.JCLQMatchData;
import com.fyzk.utils.HelpUrlConstants;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.view.BottomView;
import com.fyzk.view.BottomView.onBottomClickListener;
import com.fyzk.view.DownMenuPopupwindow;
import com.fyzk.view.TopTitleView;
import com.viewpagerindicator.TabPageIndicator;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

@ContentView(R.layout.jclq)
public class JCLQFragmentActivityI extends IBaseActivity implements
        onTopTitleClickListener, HM_PopuponItemListener, OnBetCheckedListener,
        onBottomClickListener, OnFilterListener, DownMenuPopupwindow.DownMenuPopupItemListener {

    @ViewInject(R.id.jclq_toptitle_view)
    public TopTitleView topTitleView;

    @ViewInject(R.id.shop_detail_pager)
    private NoSwipeViewPager shop_detail_pager;

    private JCLQSelectPlayMethodPop top_popup;
    private JCLQFilterGameQueuePop filter_popup;

    public static List<JCLQMatchData> matchs = new ArrayList<JCLQMatchData>();

    private int popupId = 0;

    private BottomView bottomView;
    private int minChang = 2;
    private int changCi = 0;
    private JCLQTabBaseFragment curFragment = null;// 当前fragment

    private JCLQTabBaseFragment sfFragment, rfsfFragment, dxfFragment,
            sfcFragment, hgFragment;

    FragmentPagerAdapter fAdapter;

    JCLQTabBaseFragment[] fList;

    boolean[] fragmentsUpdateFlag = {false, false};

    private final int SF = 0;
    private final int RFSF = 1;
    private final int DXF = 2;
    private final int SFC = 3;
    private final int HG = 4;

    private DownMenuPopupwindow downMenu;

    // 是否从首页竞足单关进入
    private boolean isDanGuanInto = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.d("onResume");
    }

    TextView txtMinChang;

    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.d("onStart");
    }

    private void initView() {
        isDanGuanInto = getIntent().getBooleanExtra("isDan", false);

        topTitleView.setRightVisible(View.VISIBLE);
        topTitleView.setJianTouVisible(View.VISIBLE);
        topTitleView.setRight2Visible(View.VISIBLE);
        topTitleView.setOnTitleClickListener(this);
        topTitleView.setRightImg(R.drawable.ic_question);
        topTitleView.setJianTouSrc(R.drawable.arrow_down2);
        top_popup = new JCLQSelectPlayMethodPop(this,
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
        filter_popup = new JCLQFilterGameQueuePop(this,
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        filter_popup.setOnFilterListener(this);

        dxfFragment = new JCLQDXFFragment();
        rfsfFragment = new JCLQRFSFFragment();
        sfFragment = new JCLQSFFragment();
        sfcFragment = new JCLQSFCFragment();
        hgFragment = new JCLQHGFragment();

        fList = new JCLQTabBaseFragment[5];
        fList[0] = sfFragment;
        fList[1] = rfsfFragment;
        fList[2] = dxfFragment;
        fList[3] = sfcFragment;
        fList[4] = hgFragment;

        fAdapter = new JCLQAdapter(this.getSupportFragmentManager());
        shop_detail_pager.setAdapter(fAdapter);
        shop_detail_pager.setOffscreenPageLimit(fList.length);// 缓存初当前Fragment外所有的Fragement

        if (isDanGuanInto) {
            curFragment = sfcFragment;
            topTitleView.setCenterText("胜分差(单关)");
            shop_detail_pager.setCurrentItem(SFC);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (sfcFragment != null && sfcFragment.tabIndicator != null)
                        sfcFragment.tabIndicator.setCurrentItem(sfcFragment.DANGUAN);
                }
            }, 500);
//            new Thread(() -> {
//                while (true) {
//                    TabPageIndicator curTabIndicator = curFragment.tabIndicator;
//                    if (curTabIndicator != null) {
//                        runOnUiThread(() -> {
//                            curTabIndicator.setCurrentItem(sfcFragment.DANGUAN);
//                        });
//                        break;
//                    }
//                }
//            }).start();
        } else {
            curFragment = hgFragment;
            topTitleView.setCenterText("混合投注");
            shop_detail_pager.setCurrentItem(HG);
        }

        shop_detail_pager.setOnTouchListener(null);
        shop_detail_pager.addOnPageChangeListener(pageChangeListener);
        top_popup.setOnWFCheckChangedListener(wfChangedListener);
        bottomView = (BottomView) findViewById(R.id.jclq_bottom);
        bottomView.setMoRenVisibility(View.VISIBLE);
        bottomView.setMoRenText1("已选:");


        bottomView.setMoRenText2(changCi + "场");
        txtMinChang = new TextView(this);
        txtMinChang.setTextColor(getResources().getColor(R.color.gray));
        txtMinChang.setText("至少选择 " + minChang + " 场");
        txtMinChang.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        txtMinChang.setGravity(Gravity.CENTER);
        bottomView.addCenterZiDingYiView(txtMinChang);
        bottomView.setonBottomClickListener(this);

        downMenu = new DownMenuPopupwindow(this,
                AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT,
                getMenuItems());
        downMenu.setDownMenuPopupOnItemListener(this);
    }

    protected String[] getMenuItems() {
        return new String[]{"开奖公告", "玩法介绍", "投注查询"};
    }


    OnPageChangeListener pageChangeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            if (curFragment.curFragment == null) {
                switch (position) {
                    case SF:
                        // 胜负
                        sfFragment = new JCLQSFFragment();
                        break;
                    case RFSF:
                        // 让分胜负
                        rfsfFragment = new JCLQRFSFFragment();
                        break;
                    case DXF:
                        // 大小分
                        dxfFragment = new JCLQDXFFragment();
                        break;
                    case SFC:
                        // 胜负差
                        sfcFragment = new JCLQSFCFragment();
                        break;
                    case HG:
                        // 混合过关
                        hgFragment = new JCLQHGFragment();
                        break;
                    default:
                        break;
                }
            }
            Log.e("fjl", position + "---");
            curFragment.curFragment.notifyList();
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    class JCLQAdapter extends FragmentPagerAdapter {

        public JCLQAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fList[position];
        }

        @Override
        public int getCount() {
            return fList.length;
        }
    }

    OnWFCheckChangedListener wfChangedListener = new OnWFCheckChangedListener() {

        @Override
        public void onWFCheckChange(int id, boolean isChecked) {
            if (!isChecked) {
                return;
            }
            switch (id) {
                case R.id.cb_selectplaymethod_lq_sf:
                    topTitleView.setCenterText("胜负(过关)");
                    curFragment = sfFragment;
                    shop_detail_pager.setCurrentItem(SF, false);
                    curFragment.tabIndicator.setCurrentItem(sfcFragment.GUOGUAN);
                    break;
                case R.id.cb_selectplaymethod_lq_sf_d:
                    topTitleView.setCenterText("胜负(单关)");
                    curFragment = sfFragment;
                    shop_detail_pager.setCurrentItem(SF, false);
                    curFragment.tabIndicator.setCurrentItem(sfcFragment.DANGUAN);
                    break;
                case R.id.cb_selectplaymethod_lq_sfc:
                    topTitleView.setCenterText("胜分差(过关)");
                    curFragment = sfcFragment;
                    shop_detail_pager.setCurrentItem(SFC, false);
                    curFragment.tabIndicator.setCurrentItem(sfcFragment.GUOGUAN);
                    break;
                case R.id.cb_selectplaymethod_lq_sfc_d:
                    topTitleView.setCenterText("胜分差(单关)");
                    curFragment = sfcFragment;
                    shop_detail_pager.setCurrentItem(SFC, false);
                    curFragment.tabIndicator.setCurrentItem(sfcFragment.DANGUAN);
                    break;
                case R.id.cb_selectplaymethod_hg_lq:
                    topTitleView.setCenterText("混合过关");
                    curFragment = hgFragment;
                    shop_detail_pager.setCurrentItem(HG, false);
                    break;
                case R.id.cb_selectplaymethod_dxf_lq:
                    topTitleView.setCenterText("大小分(过关)");
                    curFragment = dxfFragment;
                    shop_detail_pager.setCurrentItem(DXF, false);
                    curFragment.tabIndicator.setCurrentItem(sfcFragment.GUOGUAN);
                    break;
                case R.id.cb_selectplaymethod_dxf_lq_d:
                    topTitleView.setCenterText("大小分(单关)");
                    curFragment = dxfFragment;
                    shop_detail_pager.setCurrentItem(DXF, false);
                    curFragment.tabIndicator.setCurrentItem(sfcFragment.DANGUAN);
                    break;
                case R.id.cb_selectplaymethod_lq_rqsf:
                    topTitleView.setCenterText("让分胜负(过关)");
                    curFragment = rfsfFragment;
                    shop_detail_pager.setCurrentItem(RFSF, false);
                    curFragment.tabIndicator.setCurrentItem(sfcFragment.GUOGUAN);
                    break;
                case R.id.cb_selectplaymethod_lq_rqsf_d:
                    topTitleView.setCenterText("让分胜负(单关)");
                    curFragment = rfsfFragment;
                    shop_detail_pager.setCurrentItem(RFSF, false);
                    curFragment.tabIndicator.setCurrentItem(sfcFragment.DANGUAN);
                    break;
            }
            top_popup.dismiss();
            curFragment.curFragment.clearSel();
            onBetChecked();//切换玩法刷新场次信息
        }
    };

    public void setBtmView() {
        if (bottomView != null) {
            bottomView.setMoRenText2(changCi + "场");
            txtMinChang.setText("至少选择 " + minChang + " 场");
        }
    }

    @Override
    public void onLeftClick() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onCenterClick() {
        top_popup.showAsDropDown(topTitleView);
    }

    @Override
    public void onRightClick() {
        toHelp();
    }

    @Override
    public void onRight2Click() {
        filter_popup.setGames(curFragment.curFragment.getTeams(),
                curFragment.curFragment.teams_sel);
        filter_popup.showAsDropDown(topTitleView);
    }

    @Override
    public void popupShow() {
        topTitleView.setJianTouRotate_shun();
    }

    @Override
    public void onBetChecked() {
        changCi = curFragment.curFragment.countChangCi();
        if (curFragment.curFragment.isDanguan) {
            minChang = 1;
        } else {
            minChang = 2;
        }
        setBtmView();
    }

    @Override
    public void popupDismiss() {
        topTitleView.setJianTouRotate_ni();

    }

    protected TopTitleView getTopView() {
        return topTitleView;
    }

    /**
     * 进入玩法介绍
     */
    public void toHelp() {
        if (getTopView() != null) {
            downMenu.showPopupWindow(getTopView());
        } else {
            Intent intent = new Intent(getContext(), InfoDetailActivity.class);
            intent.putExtra(IntentParamUtils.TITLE, getHelpTitle());
            intent.putExtra(IntentParamUtils.URL, getHelpUrl());
            startActivity(intent);
        }
    }

    @Override
    public void onMenuItem(int position) {
        Intent intent = null;
        switch (position) {
            case 0:
                intent = new Intent();
                intent.setClass(getContext(), JLPrizeActivity.class);
                intent.putExtra(IntentParamUtils.LOTTERYID, LotteryIDUtils.JLSF_LOTTERY_ID_INT);
                break;
            case 1:
                intent = new Intent(getContext(), InfoDetailActivity.class);
                intent.putExtra(IntentParamUtils.TITLE, getHelpTitle());
                intent.putExtra(IntentParamUtils.URL, getHelpUrl());
                break;
            case 2:
                if (MySharedPreferences.getInstance().getLoginStatus()) {
                    intent = new Intent(getContext(), CommonBetActivity.class);
                    intent.putExtra(IntentParamUtils.LOTTERYID, LotteryIDUtils.JLSF_LOTTERY_ID_INT);
                } else {
                    AppLotteryInfos.clear();
                    ViewCallBack.getInstance().countDownObjs.clear();
                    ActivityTaskManager.getInstance().closeAllActivity();
                    intent = new Intent(getContext(), LoginActivity.class);
                }
                break;
            default:
                break;
        }
        try {
            startActivity(intent);
        } catch (Exception e) {
            LogUtil.v(e.getMessage());
        }
    }

    @Override
    public void menuDismiss() {

    }

    @Override
    public void menuShow() {

    }

    private String getHelpUrl() {
        return HelpUrlConstants.Help_JCLQ;
    }

    private String getHelpTitle() {
        return getString(R.string.help_jclq);
    }

    @Override
    public void onBottomLeftClick() {
        curFragment.curFragment.clear();
        changCi = 0;
        setBtmView();
    }

    @Override
    public void onBottomRightClick() {
        if (changCi < minChang) {
            AppToast.getToast().show("至少选择" + minChang + "场 再进行投注");
        } else {
            matchs.clear();
            for (JCLQResponseInfo info : curFragment.curFragment.infos) {
                matchs.addAll(info.matchDatas);
            }

            Intent intent = new Intent();
            switch (curFragment.curFragment.lotteryId) {
                case LotteryIDUtils.JLSF_LOTTERY_ID_INT:
                    intent.setClass(getContext(), JCLQSFPayActivity.class);
                    break;
                case LotteryIDUtils.JLRSF_LOTTERY_ID_INT:
                    intent.setClass(getContext(), JCLQRSFPayActivity.class);
                    break;
                case LotteryIDUtils.JLSFC_LOTTERY_ID_INT:
                    intent.setClass(getContext(), JCLQSFCPayActivity.class);
                    break;
                case LotteryIDUtils.JLDXF_LOTTERY_ID_INT:
                    intent.setClass(getContext(), JCLQDXFPayActivity.class);
                    break;
                case LotteryIDUtils.JLHH_LOTTERY_ID_INT:
                    intent.setClass(getContext(), JCLQHGPayActivity.class);
                    break;
                default:
                    break;
            }
            intent.putExtra(IntentParamUtils.LOTTERYID,
                    curFragment.curFragment.lotteryId);
            intent.putExtra(IntentParamUtils.TYPE_GUOGUAN,
                    curFragment.curFragment.isDanguan);
            startActivityForResult(intent, 0x6);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        onBetChecked();
        curFragment.curFragment.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onFilter(ArrayList<String> teams_sel) {
        curFragment.curFragment.onFilterOK(teams_sel);
    }

    @Override
    public void onItem(int position) {

    }

}
